package com.hlkj.pay.controller.common;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.framework.common.util.date.LocalDateTimeUtils;
import com.hlkj.pay.app.common.ITemplateAppService;
import com.hlkj.pay.app.transfer.TemplateDoToResp;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.common.TemplateQueryDto;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.infrastructure.model.common.TemplateDO;
import com.hlkj.pay.service.common.ITemplateService;
import com.hlkj.pay.vo.common.req.*;
import com.hlkj.pay.vo.common.resp.TemplateResp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Tag(name = "短信模板配置")
@RestController
@RequestMapping("/v1/common/message/template")
@RequiredArgsConstructor
@Slf4j
public class TemplateController extends BaseController {
    private final ITemplateService templateService;
    private final ITemplateAppService templateAppService;
    @Operation(summary = "分页查询")
    @GetMapping("/page")
    CommonResult<PageResult<TemplateResp>> queryTemplatePage(@Validated TemplatePageReq pageParam){
        TemplateQueryDto queryDO = BeanUtil.copyProperties(pageParam, TemplateQueryDto.class);
        queryDO.setTemplateName(null);
        queryDO.setTemplateLikeName(pageParam.getTemplateName());
        if (StringUtils.hasText(pageParam.getStartTime())) {
            try {
                LocalDateTime startTime = LocalDateTimeUtil.parse(pageParam.getStartTime(),
                        DatePattern.NORM_DATE_FORMATTER);
                queryDO.setStartSendTime(LocalDateTimeUtils.datatimeToTimestamp(startTime));
            } catch (Exception e) {
                log.warn("queryTemplatePage cover startTime error:{}", e.getMessage());
            }
        }
        if (StringUtils.hasText(pageParam.getEndTime())) {
            try {
                LocalDateTime endTime = LocalDateTimeUtil.parse(pageParam.getEndTime(),
                        DatePattern.NORM_DATE_FORMATTER);
                //+ 1 day - 1 s
                LocalDateTime localDateTime = endTime.plusDays(1).plusSeconds(-1);
                queryDO.setEndSendTime(LocalDateTimeUtils.datatimeToTimestamp(localDateTime));
            } catch (Exception e) {
                log.warn("queryTemplatePage cover endTime error:{}", e.getMessage());
            }
        }
        PageResult<TemplateDO> pageResult = templateService.queryPage(queryDO);
        List<TemplateDO> list = pageResult.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(pageResult, Collections.emptyList());
        }
        List<TemplateResp> templateResps = TemplateDoToResp.INSTANCE.doToRespList(list);
        return buildPageResult(pageResult, templateResps);
    };

    @Operation(summary = "不分页查询")
    @GetMapping("/list")
    CommonResult<List<TemplateResp>> queryTemplateList(@Validated TemplatePageReq pageParam){
        TemplateQueryDto queryDO = BeanUtil.copyProperties(pageParam, TemplateQueryDto.class);
        queryDO.setTemplateName(null);
        queryDO.setTemplateLikeName(pageParam.getTemplateName());
        if (StringUtils.hasText(pageParam.getStartTime())) {
            try {
                LocalDateTime startTime = LocalDateTimeUtil.parse(pageParam.getStartTime(),
                        DatePattern.NORM_DATE_FORMATTER);
                queryDO.setStartSendTime(LocalDateTimeUtils.datatimeToTimestamp(startTime));
            } catch (Exception e) {
                log.warn("queryTemplatePage cover startTime error:{}", e.getMessage());
            }
        }
        if (StringUtils.hasText(pageParam.getEndTime())) {
            try {
                LocalDateTime endTime = LocalDateTimeUtil.parse(pageParam.getEndTime(),
                        DatePattern.NORM_DATE_FORMATTER);
                //+ 1 day - 1 s
                LocalDateTime localDateTime = endTime.plusDays(1).plusSeconds(-1);
                queryDO.setEndSendTime(LocalDateTimeUtils.datatimeToTimestamp(localDateTime));
            } catch (Exception e) {
                log.warn("queryTemplatePage cover endTime error:{}", e.getMessage());
            }
        }
        PageResult<TemplateDO> pageResult = templateService.queryPage(queryDO);
        List<TemplateDO> list = pageResult.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(pageResult, Collections.emptyList());
        }
        List<TemplateResp> templateResps = TemplateDoToResp.INSTANCE.doToRespList(list);
        return buildPageResult(pageResult, templateResps);
    };
    @Operation(summary = "详情查询")
    @GetMapping("/detail")
    CommonResult<TemplateResp> detail(@RequestParam(name = "templateCode") String templateCode){
        TemplateDO detail = templateService.detail(templateCode);
        if (detail == null) {
            return CommonResult.success(null);
        }
        TemplateResp templateDetailResp = TemplateDoToResp.INSTANCE.doToResp(detail);
        return CommonResult.success(templateDetailResp);
    }

    @Operation(summary = "新增消息模板")
    @PostMapping("") CommonResult<String> addTemplate(@Validated @RequestBody AddTemplateReq addTemplateReq){
        return templateAppService.addTemplate(addTemplateReq);
    };
    

    @Operation(summary = "修改消息模板")
    @PutMapping("")
    CommonResult<Void> updateTemplate(@Validated @RequestBody UpdateTemplateReq updateTemplateReq){
        return templateAppService.updateTemplate(updateTemplateReq);
    };

    @Operation(summary = "删除消息模板")
    @DeleteMapping("")
    CommonResult<Void> deleteTemplate(@Validated @RequestBody DeleteCodeReq deleteCodeReq){
        return templateAppService.deleteTemplate(deleteCodeReq.getCode());
    };

    @Operation(summary = "消息模板上下架")
    @PutMapping("/status")
    CommonResult<Void> statusUpdate(@RequestBody TemplateStatusReq templateStatusReq){
        return templateAppService.statusUpdate(templateStatusReq.getTemplateCode(),
                CommonEnum.TEMPLATE_STATUS.from(templateStatusReq.getStatus()));
    };

}
